package com.micro.service.auth.server.login.wechat;


import com.micro.service.account.share.dto.UserBaseDto;
import com.micro.service.account.share.service.UserBaseService;
import com.micro.service.auth.server.model.User;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @author lvxiucai
 * @description 微信登录认证
 * @date 2019/9/25
 */
public class WechatAuthenticationProvider implements AuthenticationProvider {

    private UserBaseService userBaseService;
    /*
     * (non-Javadoc)
     *
     * @see org.springframework.security.authentication.AuthenticationProvider#
     * authenticate(org.springframework.security.core.Authentication)
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        WechatAuthenticationToken authenticationToken = (WechatAuthenticationToken) authentication;

        UserBaseDto userBaseDto = userBaseService.loadUserByWechatOpenid((String) authenticationToken.getPrincipal());
        if (userBaseDto == null) {
            throw new InternalAuthenticationServiceException("微信登录--无法获取用户信息");
        }
        UserDetails user = new User(userBaseDto.getId(),userBaseDto.getName(),userBaseDto.getPassword(),userBaseDto.getHeadImg(),userBaseDto.getMobile());


        WechatAuthenticationToken authenticationResult = new WechatAuthenticationToken(user, user.getAuthorities());

        authenticationResult.setDetails(authenticationToken.getDetails());

        return authenticationResult;
    }

    /*
     * (non-Javadoc)
     *
     * @see org.springframework.security.authentication.AuthenticationProvider#
     * supports(java.lang.Class)
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return WechatAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public UserBaseService getUserBaseService() {
        return userBaseService;
    }

    public void setUserBaseService(UserBaseService userBaseService) {
        this.userBaseService = userBaseService;
    }
}
